<template>
  <div class="layer-tree">
    <div v-if="layerStore.layers.length === 0" class="empty-tip">
      <el-icon size="48" color="#dcdfe6"><FolderOpened /></el-icon>
      <p>暂无图层</p>
      <el-text type="info" size="small">点击"添加图层"按钮开始添加</el-text>
    </div>
    
    <div v-else>
      <!-- 图层列表 -->
      <div class="layer-list">
        <div
          v-for="(layer, index) in sortedLayers"
          :key="layer.id"
          class="layer-item"
          :class="{ active: selectedLayerId === layer.id }"
          @click="selectLayer(layer.id)"
        >
          <!-- 拖拽手柄 -->
          <div class="drag-handle" @mousedown="startDrag(layer.id, $event)">
            <el-icon><Rank /></el-icon>
          </div>
          
          <!-- 图层类型图标 -->
          <div class="layer-icon">
            <el-icon>
              <component :is="getLayerIcon(layer.type)" />
            </el-icon>
          </div>
          
          <!-- 图层名称 -->
          <div class="layer-name" :title="layer.name">
            {{ layer.name }}
          </div>
          
          <!-- 图层控制按钮 -->
          <div class="layer-controls">
            <!-- 可见性切换 -->
            <el-button
              text
              size="small"
              @click.stop="toggleVisible(layer.id)"
              :class="{ 'visibility-off': !layer.visible }"
            >
              <el-icon>
                <component :is="layer.visible ? 'View' : 'Hide'" />
              </el-icon>
            </el-button>
            
            <!-- 缩放到图层 -->
            <el-button
              text
              size="small"
              @click.stop="zoomToLayer(layer.id)"
              title="缩放到图层"
            >
              <el-icon><ZoomIn /></el-icon>
            </el-button>
            
            <!-- 删除图层 -->
            <el-button
              text
              size="small"
              type="danger"
              @click.stop="removeLayer(layer.id)"
              title="删除图层"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 图层详情面板 -->
      <div v-if="selectedLayer" class="layer-details">
        <el-divider>图层详情</el-divider>
        <el-descriptions :column="1" size="small" border>
          <el-descriptions-item label="名称">
            {{ selectedLayer.name }}
          </el-descriptions-item>
          <el-descriptions-item label="类型">
            {{ getLayerTypeName(selectedLayer.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedLayer.visible ? 'success' : 'info'" size="small">
              {{ selectedLayer.visible ? '显示' : '隐藏' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="URL" v-if="selectedLayer.url">
            <el-text size="small" class="url-text" :title="selectedLayer.url">
              {{ selectedLayer.url }}
            </el-text>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { 
  FolderOpened, 
  Rank, 
  View, 
  Hide, 
  ZoomIn, 
  Delete,
  Box,
  Map,
  DataLine,
  Location
} from '@element-plus/icons-vue'
import { useLayerStore } from '../stores/layerStore'
import { ElMessage, ElMessageBox } from 'element-plus'

const layerStore = useLayerStore()
const selectedLayerId = ref(null)
const dragLayerId = ref(null)
const isDragging = ref(false)

// 计算属性
const sortedLayers = computed(() => {
  return [...layerStore.layers].reverse() // 反转数组，最后添加的在上面
})

const selectedLayer = computed(() => {
  return layerStore.layers.find(layer => layer.id === selectedLayerId.value)
})

// 选择图层
const selectLayer = (layerId) => {
  selectedLayerId.value = selectedLayerId.value === layerId ? null : layerId
}

// 切换图层可见性
const toggleVisible = (layerId) => {
  layerStore.toggleLayerVisible(layerId)
}

// 删除图层
const removeLayer = async (layerId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个图层吗？', '确认删除', {
      type: 'warning'
    })
    layerStore.removeLayer(layerId)
    if (selectedLayerId.value === layerId) {
      selectedLayerId.value = null
    }
    ElMessage.success('图层删除成功')
  } catch {
    // 用户取消删除
  }
}

// 缩放到图层
const zoomToLayer = (layerId) => {
  const layer = layerStore.layers.find(l => l.id === layerId)
  if (layer && layer.layerInstance) {
    try {
      if (layer.layerInstance.flyTo) {
        layer.layerInstance.flyTo()
      } else if (layer.layerInstance.zoomTo) {
        layer.layerInstance.zoomTo()
      } else if (layer.layerInstance.centerAt) {
        layer.layerInstance.centerAt()
      }
    } catch (error) {
      console.warn('无法缩放到图层:', error)
      ElMessage.warning('无法缩放到该图层')
    }
  }
}

// 获取图层类型图标
const getLayerIcon = (type) => {
  const iconMap = {
    '3dtiles': 'Box',
    'tms': 'Map',
    'wms': 'Map',
    'geojson': 'Location'
  }
  return iconMap[type] || 'DataLine'
}

// 获取图层类型名称
const getLayerTypeName = (type) => {
  const nameMap = {
    '3dtiles': '3D Tiles',
    'tms': 'TMS瓦片',
    'wms': 'WMS服务',
    'geojson': 'GeoJSON'
  }
  return nameMap[type] || type.toUpperCase()
}

// 拖拽相关
const startDrag = (layerId, event) => {
  dragLayerId.value = layerId
  isDragging.value = true
  
  const startY = event.clientY
  let currentIndex = layerStore.layers.findIndex(l => l.id === layerId)
  
  const handleMouseMove = (e) => {
    const deltaY = e.clientY - startY
    const itemHeight = 60 // 估算的图层项高度
    const steps = Math.floor(deltaY / itemHeight)
    
    if (steps !== 0) {
      const newIndex = Math.max(0, Math.min(layerStore.layers.length - 1, currentIndex - steps))
      if (newIndex !== currentIndex) {
        layerStore.setLayerOrder(layerId, newIndex)
        currentIndex = newIndex
      }
    }
  }
  
  const handleMouseUp = () => {
    isDragging.value = false
    dragLayerId.value = null
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  
  event.preventDefault()
}
</script>

<style scoped>
.layer-tree {
  user-select: none;
}

.empty-tip {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-tip p {
  margin: 12px 0 8px;
  font-size: 14px;
}

.layer-list {
  max-height: 400px;
  overflow-y: auto;
}

.layer-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 2px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.layer-item:hover {
  background-color: #f5f7fa;
}

.layer-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.drag-handle {
  cursor: grab;
  color: #c0c4cc;
  margin-right: 8px;
  padding: 2px;
}

.drag-handle:hover {
  color: #409eff;
}

.drag-handle:active {
  cursor: grabbing;
}

.layer-icon {
  margin-right: 8px;
  color: #409eff;
}

.layer-name {
  flex: 1;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0;
}

.layer-controls {
  display: flex;
  gap: 2px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.layer-item:hover .layer-controls {
  opacity: 1;
}

.layer-controls .el-button {
  padding: 4px !important;
  min-height: auto !important;
}

.visibility-off {
  opacity: 0.5;
}

.layer-details {
  margin-top: 16px;
}

.url-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
}

/* 滚动条样式 */
.layer-list::-webkit-scrollbar {
  width: 4px;
}

.layer-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.layer-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.layer-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>